package com.dddpeter.app.controller;

import com.dddpeter.app.entity.SysDictData;
import com.dddpeter.app.entity.SysDictType;
import com.dddpeter.app.service.SysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/dict")
@CrossOrigin(origins = "*")
public class SysDictController {
    
    @Autowired
    private SysDictService dictService;
    
    // ========== 字典类型接口 ==========
    
    @GetMapping("/types")
    public ResponseEntity<Map<String, Object>> getAllDictTypes() {
        try {
            List<SysDictType> types = dictService.getAllDictTypes();
            return ResponseEntity.ok(createSuccessResponse(types, "获取字典类型成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("获取字典类型失败: " + e.getMessage()));
        }
    }
    
    @GetMapping("/types/{dictType}")
    public ResponseEntity<Map<String, Object>> getDictTypeByType(@PathVariable String dictType) {
        try {
            SysDictType type = dictService.getDictTypeByType(dictType);
            if (type != null) {
                return ResponseEntity.ok(createSuccessResponse(type, "获取字典类型成功"));
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(createErrorResponse("字典类型不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("获取字典类型失败: " + e.getMessage()));
        }
    }
    
    @PostMapping("/types")
    public ResponseEntity<Map<String, Object>> createDictType(@RequestBody SysDictType dictType) {
        try {
            SysDictType created = dictService.createDictType(dictType);
            return ResponseEntity.status(HttpStatus.CREATED)
                    .body(createSuccessResponse(created, "创建字典类型成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(createErrorResponse("创建字典类型失败: " + e.getMessage()));
        }
    }
    
    @PutMapping("/types/{dictId}")
    public ResponseEntity<Map<String, Object>> updateDictType(@PathVariable Long dictId, 
                                                               @RequestBody SysDictType dictType) {
        try {
            SysDictType updated = dictService.updateDictType(dictId, dictType);
            return ResponseEntity.ok(createSuccessResponse(updated, "更新字典类型成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(createErrorResponse("更新字典类型失败: " + e.getMessage()));
        }
    }
    
    @DeleteMapping("/types/{dictId}")
    public ResponseEntity<Map<String, Object>> deleteDictType(@PathVariable Long dictId) {
        try {
            dictService.deleteDictType(dictId);
            return ResponseEntity.ok(createSuccessResponse(null, "删除字典类型成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(createErrorResponse("删除字典类型失败: " + e.getMessage()));
        }
    }
    
    // ========== 字典数据接口 ==========
    
    @GetMapping("/data/type/{dictType}")
    public ResponseEntity<Map<String, Object>> getDictDataByType(@PathVariable String dictType) {
        try {
            List<SysDictData> dataList = dictService.getDictDataByType(dictType);
            return ResponseEntity.ok(createSuccessResponse(dataList, "获取字典数据成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("获取字典数据失败: " + e.getMessage()));
        }
    }
    
    @GetMapping("/data")
    public ResponseEntity<Map<String, Object>> getAllDictData() {
        try {
            List<SysDictData> dataList = dictService.getAllDictData();
            return ResponseEntity.ok(createSuccessResponse(dataList, "获取所有字典数据成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("获取字典数据失败: " + e.getMessage()));
        }
    }
    
    @GetMapping("/data/{dictCode}")
    public ResponseEntity<Map<String, Object>> getDictDataById(@PathVariable Long dictCode) {
        try {
            SysDictData data = dictService.getDictDataById(dictCode);
            if (data != null) {
                return ResponseEntity.ok(createSuccessResponse(data, "获取字典数据成功"));
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(createErrorResponse("字典数据不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("获取字典数据失败: " + e.getMessage()));
        }
    }
    
    @PostMapping("/data")
    public ResponseEntity<Map<String, Object>> createDictData(@RequestBody SysDictData dictData) {
        try {
            SysDictData created = dictService.createDictData(dictData);
            return ResponseEntity.status(HttpStatus.CREATED)
                    .body(createSuccessResponse(created, "创建字典数据成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(createErrorResponse("创建字典数据失败: " + e.getMessage()));
        }
    }
    
    @PutMapping("/data/{dictCode}")
    public ResponseEntity<Map<String, Object>> updateDictData(@PathVariable Long dictCode, 
                                                               @RequestBody SysDictData dictData) {
        try {
            SysDictData updated = dictService.updateDictData(dictCode, dictData);
            return ResponseEntity.ok(createSuccessResponse(updated, "更新字典数据成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(createErrorResponse("更新字典数据失败: " + e.getMessage()));
        }
    }
    
    @DeleteMapping("/data/{dictCode}")
    public ResponseEntity<Map<String, Object>> deleteDictData(@PathVariable Long dictCode) {
        try {
            dictService.deleteDictData(dictCode);
            return ResponseEntity.ok(createSuccessResponse(null, "删除字典数据成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(createErrorResponse("删除字典数据失败: " + e.getMessage()));
        }
    }
    
    // ========== 便捷接口 ==========
    
    /**
     * 获取文章分类列表
     */
    @GetMapping("/categories")
    public ResponseEntity<Map<String, Object>> getArticleCategories() {
        try {
            List<SysDictData> categories = dictService.getArticleCategories();
            return ResponseEntity.ok(createSuccessResponse(categories, "获取文章分类成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("获取文章分类失败: " + e.getMessage()));
        }
    }
    
    // ========== 工具方法 ==========
    
    private Map<String, Object> createSuccessResponse(Object data, String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("data", data);
        response.put("message", message);
        response.put("timestamp", System.currentTimeMillis());
        return response;
    }
    
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("error", message);
        response.put("timestamp", System.currentTimeMillis());
        return response;
    }
}

